<template>
  <view>
    <el-divider content-position="left">
      <span class="h1">文章管理</span>
    </el-divider>
    <h1>分类编辑</h1>
    <br>
    <div>
      <el-button type="primary" :dark="isDark" plain @click="addData">+ 新增</el-button>
      <el-button type="danger" :dark="isDark" plain @click="batchDel">- 批量删除</el-button>
    </div>
    <br>
    <div>
      <el-input v-model="query.categoryName" placeholder="categoryName" style="width: 200px"></el-input>
      <el-button type="primary" :dark="isDark" plain @click="search">查询</el-button>
      <el-button type="primary" :dark="isDark" plain @click="reset">重置</el-button>
    </div>
    <br>
    <!-- element-plus表格 -->
    <el-table ref="tableRef" :data="formData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column prop="categoryName" label="类别" />
      <el-table-column prop="description" label="描述" />
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :active-value=1 :inactive-value=0 disabled></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="edit(row)">编辑
          </el-button>
          <el-popconfirm title="确定要删除吗?" @confirm="delData(row)" confirm-button-text="是" cancel-button-text="否">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <br>

    <!-- element-plus分页 -->
    <el-pagination v-model:currentPage="query.current" :page-size="query.pageSize" layout="total,  prev, pager, next, jumper"
      :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 新增/编辑表单 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
      <el-form :model="formDTO" ref="vForm" :rules="rules" label-position="right" label-width="80px" size="medium"
        @submit.prevent>
        <el-form-item label="ID" prop="categoryId">
          <el-input v-model="formDTO.categoryId" type="text" clearable :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="categoryName">
          <el-input v-model="formDTO.categoryName" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formDTO.description" type="text" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" class="label-right-align">
          <el-switch v-model="formDTO.status" :active-value=1 :inactive-value=0></el-switch>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </view>
</template>

<script setup>
import { ref,onMounted } from "vue";
import { category } from '@/api'
import { ElNotification } from 'element-plus'
//分页数据
const pageSize = ref(10);
const total = ref(0);
//删除列表
const delList = ref([]);
const tableRef = ref();
//弹出层
const dialogVisible = ref(false);
const dialogTitle = ref("");
const vForm = ref(null);

//表单数据
const formData = ref([]);

//验证规则
const rules = ref({
  categoryId: [
    {
      pattern: /^[-]?\d+(\.\d+)?$/,
      trigger: ["blur", "change"],
      message: "",
    },
  ],
  categoryName: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
  description: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
  status: [
    {
      required: true,
      message: "字段值不可为空",
    },
  ],
});

//提交表单结构
const formDTO = ref({
  categoryId: "",
  categoryName: "",
  description: "",
  status: "",
});

//查询参数
const query = ref({
  categoryName: "",
  current: 1,
  pageSize: 10,
});


/**
 * 数据处理-------------------------
 */

/**
 * 编辑
 */
const edit = (row) => {
  dialogTitle.value = "编辑表单";
  dialogVisible.value = true;
  if (vForm.value) {
    vForm.value.resetFields(); // 确保调用resetFields来重置验证
  }
  // 深拷贝form
  for (let key in formDTO.value) {
    formDTO.value[key] = row[key];
  }
  console.log(row);
};

/**
 * 删除
 */
const delData = (row) => {
  console.log(row);
  del([row.categoryId]);
};

/**
 * 批量删除
 */
const batchDel = () => {
  del(delList.value);
  console.log(delList.value);
  // 清空选中列表
  tableRef.value.clearSelection();
};

/**
 * 重置
 */
const reset = () => {
  query.value = {
    categoryName: "",
    current: 1,
    pageSize: 10,
  }
  total.value = 1
  get()
}

/**
 * 新增
 */
const addData = () => {
  dialogTitle.value = "新增表单";
  dialogVisible.value = true;
  formDTO.value = {};
  // 重置表单验证状态
  if (vForm.value) {
    vForm.value.resetFields();
  }
};

/**
 * 提交
 */
const submit = () => {
  dialogVisible.value = false;
  if (dialogTitle.value === '编辑表单') {
    //调用修改接口
    put(formDTO.value);
  } else if (dialogTitle.value === '新增表单'){
    //调用添加接口
    add(formDTO.value);
  }
  console.log(formDTO.value);
};

/**
 * 查询
 */
const search = () => {
  category.list(query.value).then(res => {
    console.log(res.data);
    formData.value = res.data.data.records
    total.value = res.data.data.total
  })
}


/**
 * 监听分页
 */
const handleSizeChange = (val) => {
  pageSize.value = val;
  getlist();
  console.log(formDTO.value);
};

/**
 * 选择
 */
const handleSelectionChange = (val) => {
  //筛出id列表
  delList.value = val.map((item) => item.categoryId);
  console.log(val);
};

const handleCurrentChange = (val) =>{
		console.log(val);
		get(query.value)
	}

/**
 * 接口调用------------------------------------------------------------
 */

const add = (data) => {
  console.log("添加数据:", data)
  category.add(data).then(res => {
      ElNotification({
      title: 'Success',
      message: '添加成功',
      type: 'success',
    })
    console.log("新增成功:", res)
    get(query.value)
  }).catch(res=>{
    ElNotification({
      title: 'Error',
      message: '新增失败',
      type: 'error',
    })
  })}

const del = (data) => {
  category.del(data).then(res => {
    if(res.data.code===0){
      ElNotification({
        title: 'Warning',
        message: '当前分类关联了文章,不能删除',
        type: 'warning',
      })
    } else if(res.data.code===200){
      ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    })}
    console.log("删除数据:", res)
    get(query.value)
  }).catch(res=>{
    ElNotification({
      title: 'Error',
      message: '删除失败',
      type: 'error',
    })
  })
}

const get = (data) => {
  category.list(data).then(res => {
    formData.value = res.data.data.records
    total.value = res.data.data.total
    console.log("获取数据:", res)
  })
}

const put = (data) => {
  console.log("修改数据:", data)
  category.edit(data).then(res => {
    if(res.data.code===0){
      ElNotification({
        title: 'Warning',
        message: '修改失败，请检查填写内容',
        type: 'warning',
      })
    } else if(res.data.code===200){
      ElNotification({
      title: 'Success',
      message: '编辑成功',
      type: 'success',
    })
    }
      
    console.log("编辑成功:", res.data.code)
    get(query.value)
  }).catch(res=>{
    ElNotification({
      title: 'Error',
      message: '编辑失败',
      type: 'error',
    })
  })
}
/**
 * 生命周期
 */
onMounted(() => {
  get(query.value)
})

</script>

<style scoped>
.h1 {
  font-size: 25px;
}
</style>
